package com.steam.xbcc.service.impl;

import com.steam.xbcc.constants.RedisSmsConstants;
import com.steam.xbcc.domain.Blacklist;
import com.steam.xbcc.domain.MessageSms;
import com.steam.xbcc.dto.RedisSmsDto;
import com.steam.xbcc.dto.SmsCodeDto;
import com.steam.xbcc.enums.GlobalExceptionCode;
import com.steam.xbcc.exception.GlobalCustomException;
import com.steam.xbcc.properties.SmsRegisterProperties;
import com.steam.xbcc.service.IBlacklistService;
import com.steam.xbcc.service.IMessageSmsService;
import com.steam.xbcc.service.IVerifyCodeService;
import com.steam.xbcc.util.AssertUtil;
import com.steam.xbcc.util.StrUtils;
import com.steam.xbcc.util.VerifyCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class VerifyCodeServiceImpl implements IVerifyCodeService {

    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;
    @Autowired
    private IMessageSmsService messageSmsService;
    @Autowired
    private SmsRegisterProperties smsRegisterProperties;
    @Autowired
    private IBlacklistService blacklistService;

    @Override
    public String image(String imageCodeKey) {
        //使用工具类生成图形验证码
        String code = StrUtils.getComplexRandomString(1);//1213
        //保存到redis
        redisTemplate.opsForValue().set(imageCodeKey,code,5, TimeUnit.MINUTES);
        //使用工具类生成图形验证码编码之后的base64的字符串
        String base64Str = VerifyCodeUtils.verifyCode(110, 40, code);
        return base64Str;
    }

    @Override
    public void verify(SmsCodeDto smsCodeDto) {
        //判断手机号码
        /*if (smsCodeDto.getMobile() == null){
            throw new GlobalCustomException(GlobalErrorCode.PHONE_IS_NULL);
        }*/
        String mobile = smsCodeDto.getMobile();
        AssertUtil.isPhone(mobile, GlobalExceptionCode.PARAM_IS_NULL_ERROR);
        Blacklist blacklist = blacklistService.selectByPhone(mobile);
        AssertUtil.isNull(blacklist, GlobalExceptionCode.PHONE_IS_NOT_NULL);
        //判断图形验证码
        /*if (smsCodeDto.getImageCode() == null && smsCodeDto.getImageCode() != smsCodeDto.getImageCodeKey()){
            throw new GlobalCustomException(GlobalErrorCode.IMAGE_IS_ERROR);
        }*/
        String imageCodeKey = String.valueOf(redisTemplate.opsForValue().get(smsCodeDto.getImageCodeKey()));
        AssertUtil.isEqualsIgnoreCase(smsCodeDto.getImageCode(),imageCodeKey, GlobalExceptionCode.IMAGE_IS_ERROR);
        //获取手机验证码
        /*String rediskey = "register:" + smsCodeDto.getMobile();*/
        String rediskey = String.format(RedisSmsConstants.PHONE_BUSINESS_KEY, mobile);
        Object obj = redisTemplate.opsForValue().get(rediskey);
        Date date = new Date();
        String code = "";
        if (obj != null){
            /*String[] split = obj.toString().split(":");
            Long time = Long.valueOf(split[1]);*/
            RedisSmsDto dto = (RedisSmsDto) obj;
            /*if (date.getTime() - time < 60000){
                throw new GlobalCustomException(GlobalExceptionCode.OPERATING_FREQUENTLY_ERROR);
            }*/
            boolean boo = (date.getTime() - dto.getTime()) < smsRegisterProperties.getInterval();
            AssertUtil.isFalse(boo, GlobalExceptionCode.OPERATING_FREQUENTLY_ERROR);
            code = dto.getCode();
        } else {
            code = StrUtils.getRandomString(smsRegisterProperties.getCodesize());
        }
        RedisSmsDto redisSmsDto = new RedisSmsDto(code, date.getTime());
        redisTemplate.opsForValue().set(rediskey, redisSmsDto, smsRegisterProperties.getExpiredtime(), TimeUnit.MILLISECONDS);
        messageSms(date, code, mobile);
    }

    private void messageSms(Date date, String code, String mobile) {
        MessageSms messageSms = new MessageSms();
        messageSms.setTitle(smsRegisterProperties.getTitle());
        String format = String.format(smsRegisterProperties.getContent(), code);
        messageSms.setContent(format);
        messageSms.setSendTime(date);
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String ip = request.getRemoteAddr();
        messageSms.setIp(ip);
        messageSms.setPhone(mobile);
        messageSmsService.insert(messageSms);
        log.info(format);
    }
}
